/**
@author : MAMAMA
@date: 2019-07-12
@description: transmition though searial port
*/
#include "Stream.h"


Stream::Stream(USART_INFO* info, ARM_DRIVER_USART* driver)
{
    this->info = info;
    this->driver = driver;
}


bool Stream::begin(int baudrate)
{
    this->info->baudrate = baudrate;
    this->driver->Initialize(0U);
    return true;
}



void Stream::write(uint8_t data)
{
    this->driver->Send(&data, 1);
}

void Stream::writeString(const char* msg)
{
    u16 i = 0;
    u8 *pstr = (u8*)msg;
    for(i=0;i<255;i++)
    {
        if(*msg == 0)
            break;
        msg++;
    }
    if(i != 255)
    {
        this->writeBytes(pstr, i);
    }
}

void Stream::writeLine(const char* msg)
{
    u8 endStr[2] = {'\r','\n'};
    this->writeString(msg);
    this->writeBytes(endStr,2);
}

void Stream::writeBytes(u8* p, u16 len)
{
    this->driver->Send(p, len);
}

u8 Stream::available(void)
{
    return this->info->trans_info.rx_que->length;
}

uint8_t Stream::read(void)
{
    static uint8_t data;
    this->driver->Receive(&data, 1);
    return data;
}

uint16_t Stream::readBytes(uint8_t* buf_in, uint16_t len)
{
    uint16_t buf_len = this->info->trans_info.rx_que->length;
    if(buf_len <= len)
    {       
        len = buf_len;
    }
    this->driver->Receive(buf_in, len);
    return len;
}

uint16_t Stream::readAll(uint8_t* buf_in)
{
    uint16_t len = this->info->trans_info.rx_que->length;
    this->driver->Receive(buf_in, len);
    return len;
}

/**
  * @brief  从缓存中读取一行数据，以\n作为判断
  * @param  保存数据的地址
  * @retval 读取数据的长度，如果没有找到\n会把所有的数据读出来
  */
u16 Stream::readLine(unsigned char* pbuf)
{
    uint16_t i = 0;
    uint16_t len = this->info->trans_info.rx_que->length;
    for(i=0;i<len;i++)
    {
        this->driver->Receive(pbuf, 1);
        if(*pbuf == '\n')
        {
            i++;
            break;
        }
        else
            pbuf++;
    }
    return i;
}

/**
  * @brief  清空接收缓存
  */
void Stream::clear_rx_buf(void)
{
    this->info->trans_info.rx_dataReady = 0;
    queue_clear(this->info->trans_info.rx_que);
    return;
}


void bitWrite(uint16_t &data, uint8_t n, bool b)
{
    uint16_t mask;
    if(b)
    {
        mask = 1;
        data = data | (mask << n);
    }
    else
    {
        mask = 0xFFFE;
        data = data & (mask << n);
    }
    return;
}

